package com.ynyr.jar.wss.config;

import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ynyr.jar.common.jpa.db.DataSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Optional;

@Configuration
@EnableJpaAuditing(auditorAwareRef = "usernameAuditor")
public class DbConfig {

    @Autowired
    private Environment environment;

    @Bean
    public DataSource customDataSource() throws SQLException {
        return DataSourceBuilder.build(environment, "spring.datasource");
    }

    @Bean
    public JPAQueryFactory JPAQueryFactory(EntityManager entityManager) {
        return new JPAQueryFactory(entityManager);
    }

    @Bean
    public AuditorAware usernameAuditor() {
        return () -> Optional.of("anonymous");
    }

}
